-module (ham_server_core).

-include("emqttd.hrl").

-include("mysql.hrl").

-export([send_msg_ham/6,send_group_ham/6,send_sub_state/4]).

send_msg_ham(_Appkey,FromUsername,Username,MsgType,Payload,Qos) ->
	case mnesia:dirty_read(url_map,Username) of 
		[] ->
			ok;
		[Record] ->
			URL = Record#url_map.url,
			Request = jsx:encode([{<<"code">>,0},{<<"from_uid">>,FromUsername},{<<"to_uid">>,Username},{<<"msg_type">>,MsgType},{<<"content">>,base64:encode(Payload)},
            	{<<"create_time">>,tools:get_unixtime()}]),
			Pid = 
				case ham_server_http_client:start_link(URL) of 
					{ok,Pid1} ->
						Pid1;
					{error,{already_started,Pid1}} ->
						Pid1
				end,
			{_,Len} = erlang:process_info(Pid,message_queue_len),
			case Len < ?PID_MESSAGE_QUEUE of 
				true -> 
					gen_server:cast(Pid,{post_request,{Request,Qos}});
				_ ->
					ok
			end					
	end.			

send_group_ham(_Appkey, FromUsername, Username,GroupId, Payload, Qos) ->
	GroupId1 = binary_to_list(GroupId),
	case mnesia:dirty_read(url_map,Username) of 
		[] ->
			ok;
		[Record] ->
			URL = Record#url_map.url,
			Request = 
				case string:sub_string(GroupId1,1,2) =:= "p@" of 
					true ->
						jsx:encode([{<<"code">>,0},{<<"from_uid">>,FromUsername},{<<"group_id">>,list_to_binary(string:sub_string(GroupId1,3,length(GroupId1)))},{<<"msg_type">>,4},{<<"content">>,base64:encode(Payload)},
	              			{<<"create_time">>,tools:get_unixtime()}]);
					false ->
						jsx:encode([{<<"code">>,0},{<<"from_uid">>,FromUsername},{<<"group_id">>,GroupId},{<<"msg_type">>,4},{<<"content">>,base64:encode(Payload)},
	              			{<<"create_time">>,tools:get_unixtime()}])
				end,	
			Pid = 
				case ham_server_http_client:start_link(URL) of 
					{ok,Pid1} ->
						Pid1;
					{error,{already_started,Pid1}} ->
						Pid1
				end,
			{_,Len} = erlang:process_info(Pid,message_queue_len),				
			case Len < ?PID_MESSAGE_QUEUE of 
				true -> 
					gen_server:cast(Pid,{post_request,{Request,Qos}});
				_ ->
					ok
			end		
	end.

send_sub_state(_Appkey, FromUsername, Username, Type) ->
	case mnesia:dirty_read(url_map,Username) of 
		[] ->
			ok;
		[Record] ->
			URL = Record#url_map.url,
			Request = jsx:encode([{<<"code">>,0},{<<"from_uid">>,FromUsername},{<<"to_uid">>,Username},{<<"msg_type">>,4},{<<"type">>,Type},
              {<<"time">>,tools:get_unixtime()}]),
			Pid = 
				case ham_server_http_client:start_link(URL) of 
					{ok,Pid1} ->
						Pid1;
					{error,{already_started,Pid1}} ->
						Pid1
				end,	
			{_,Len} = erlang:process_info(Pid,message_queue_len),			
			case Len < ?PID_MESSAGE_QUEUE of 
				true -> 
					gen_server:cast(Pid,{post_request,{Request,0}});
				_ ->
					ok
			end			
	end.